<!doctype html>
<html>
<title>jQuery平面图区域标记拖拽移动代码</title>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- <script type="text/javascript" src="../js/jquery.min.js" ></script> -->
<script type="text/javascript" src="/layui/layui.js"></script>
<script type="text/javascript" src="/context/context.js"></script>
<script type="text/javascript" src="/context/drag.js" ></script>
<link rel="stylesheet" type="text/css" href="/context/context.standalone.css">
<!-- <link rel="stylesheet" type="text/css" href="http://blog.aigouzhushou.com/layui-v2.4.3/layui-v2.4.5/css/layui.css"> -->
<style type="text/css">
html,body{margin:0;padding:0;font:14px/1.5em simsun;overflow:hidden;}
#canvas{position:absolute;left:0px;top:0px;z-index:9;border:2px dashed #ccc;padding:10px;background:#fff;}
.transparent{filter:alpha(opacity=50);-moz-opacity:0.5;-khtml-opacity:0.5;opacity:0.5;}
.box{width:200px;height:100px;cursor:move;position:absolute;top:30px;left:30px;z-index:99;}
.box .bg{width:100%;height:100%;background-color:orange;}
.box .coor{width:10px;height:10px;overflow:hidden;cursor:se-resize;position:absolute;right:0;bottom:0;background-color:red;}
/*.content{display:none;}*/
.box .content{position:absolute;left:35%;top:185%;z-index:99;text-align:center;font:bold 14px/1.5em simsun;}
pre {
    /*display: none;*/
    display: block;
    font-family: monospace;
    white-space: pre;
    margin: 1em 0px;
    background-color: rgba(255, 255, 255, 0);
    border: 0px solid #ccc;
}
#debug{position:absolute;right:10px;top:10px;z-index:88;border:1px solid #ccc;width:100px;height:100px;background:#fff;}
#toolbar{position:absolute;left:10px;top:10px;z-index:88;}

</style>
</head>
<input type="hidden" name="roomname" class="roomname" />
<body class="list" onbeforeunload="return myFunction()">
<!-- <pre id="debug"></pre> -->
<div id="hezi" style="display: flex;justify-content: flex-start;">
    <div id="toolbar">
        <!-- <input type="button" value="添加下级" class="btn" id="btn_add" /> -->
        <!--<input type="button" value="锁定区域" class="btn" id="btn_lock" />  ../images/timg.jpg-->
        <input type="button" value="保存" class="btn" id="btn_save" />
        <select id="select">
        @if($list)
            @foreach($list as $k => $one)
            <option value ="{{$one['id']}}">{{$one['name']}}</option>
            @endforeach
        @endif
        </select>
    </div>
    <!-- <div>TTTT</div> -->
    <div id="canvas">
        <img src="{{$planeJPG}}" />
    </div>
</div>
<div id="file_upload_div" style="display: none" class="text-center">
    <div class="layui-upload-drag" id="test10">
        <i class="layui-icon"></i>
        <p>点击上传，或将文件拖拽到此处</p>
    </div>
    <div class="mt-2 mb-2" id="file_name"></div>
    <div class="layui-input-inline " style="width: 100%;">
        <div class="layui-input-inline">
            <label for="type" class="layui-form-label" style="width: 100px">下级名称: </label>
        </div>
        <input type="text"  name="name" class="inputname" >
    </div>
    <div class="row w-100"></div>
    <button type="button" class="layui-btn mt-2" id="upload">开始上传</button>
</div>
<!-- <script src="http://blog.aigouzhushou.com/layui-v2.4.3/layui-v2.4.5/layui.js"></script> -->
<script>
    $('#select').change(function() {
        //图层切换
        var options=$("#select option:selected");
        let url1 = "/admin/device/location/"+options.val();
        // let url1 = '../location/'+$(this).val();
        window.location.href=url1;
        console.log(options.val());
        console.log($(this).val());
        console.log(url1);
        //二:
        // var options=$("#select option:selected");
        // console.log(options.val());
    })
        $(document).ready(function () {
             if(location.href.indexOf("#reloaded")==-1){
                location.href=location.href+"#reloaded";
                location.reload();
            }
        })
        layui.use('upload', function () {
            var upload = layui.upload;
            let cookies = document.cookie.split(',');
            let pattern = /csrftoken=(.*)/m;
            let csrf;
            for (let j = 0; j < cookies.length; j++) {
                if (pattern.test(cookies[j])) {
                    csrf = pattern.exec(cookies[j])[1];
                }
            }
            //执行实例
            var uploadInst = upload.render({
                elem: '#test10' //绑定元素
                , headers: {
                    "X-CSRFToken": csrf
                }
                , auto: false
                , bindAction: "#upload"
                , url: '/api/uploadMap' //上传接口
                ,before: function(input){
                     var data = {};
                     data.pid = $('.pid').val();
                     data.roomname = function(){return $('.roomname').val();}   //动态获取input输入的值
                     data.project = $('.project').val();
                     this.data=data;
                }
                , choose: function (obj) {
                    obj.preview(function (index, file, result) {
                        document.getElementById("file_name").innerHTML = file.name;
                    })
                }
                , done: function (res) {
                    if(res.status){
                        document.getElementsByClassName("layui-layer-close")[0].click()
                        layer.msg("上传成功");
                        window.location.reload();
                    }else{
                        layer.msg(res.msg);
                    }
                }
                , error: function () {
                    layer.msg("上传失败，请重新上传")
                }
            });
        });
    $(".inputname").bind('input propertychange', function() {
        var a = $(".inputname").val();
        $(".roomname").val(a);
    })

</script>
<script>
$(function(){
    //初始化计数器
    var num = 0;
    //区块锁定标识
    var lock = false;
    //加载layer拓展
    layer.config({
        extend: 'extend/layer.ext.js'
    });
    //右键菜单参数
    // context.init({
    //     fadeSpeed: 100,
    //     filter: function ($obj){},
    //     above: 'auto',
    //     preventDoubleContext: true,
    //     compress: false
    // });
    //调试输出方法
    function debug(msg){
        $("#debug").text(msg);
    }
    function createBox(data){
        var dataId = data.rid || '';
        var type = data.type || 1;
        var value = data.text || '';
        var color = data.color || '';
        var height = data.height || 0;
        var width = data.width || 0;
        var pageX = data.pageX || 0;
        var pageY = data.pageY || 0;
        var rid = data.rid;

        //更新计数器并记录当前计数
        var curNum = num++;
        //创建区域块 
        var pos = $("#canvas").position();
        var box = $('<div class="box" rel="'+curNum+'" dataId="'+dataId+'" type="'+type+'"><pre class="content">'+value+'</pre><div class="bg transparent" style=""></div><img style="width:25px;height:25px;" src="/icon/alarm1.gif"></div>').css({
            width : width,
            height : height,
            top : pageY > 0 ? pageY : (pos.top > 0 ? 0 : pos.top * -1 + 50),
            left : pageX > 0 ? pageX : (pos.left > 0 ? 0 : pos.left * -1 + 30)
        }).appendTo("#canvas");

        //计算文本位置
        box.find('.content').css({
            marginLeft : box.find('.content').width()/2*-1,
            // marginTop : box.find('.content').height()/2*-1
            marginTop : box.find('.content').height()/2
        });
        //创建右键菜单
        if(type == 1){
            // context.attach('.box[rel='+curNum+']', [
                // {header: '操作'},
                // {text: '进入区域', action: function(e){
                //         window.location.href='emap?projectId='+rid+'&&type=1';
                //     }
                // },
                /*{text: '更改区域尺寸', action: function(e){
                        e.preventDefault();
                        layer.prompt({
                            title: '请输入区域尺寸（宽,高），最小值：30',
                            formType: 0,
                            value: $('.box[rel='+curNum+']').width()+","+$('.box[rel='+curNum+']').height()
                        }, function(value, index, elem){
                            var reg = /^[0-9]+,[0-9]+$/;
                            if(!reg.test(value)){
                                alert('输入格式不正确，例：100,200');
                                return;
                            }
                            var size = value.split(',');
                            var box = $('.box[rel='+curNum+']');
                            box.css({
                                width : size[0] < 30 ? 30 : size[0],
                                height : size[1] < 30 ? 30 : size[1]
                            });
                            layer.close(index);
                        });
                    }
                },*/
                // {text: '删除区域', action: function(e){
                //      e.preventDefault();
                //      $('.box[rel='+curNum+']').remove();
                //     }
                // },
                // {divider: true},
                /*{header: '更改颜色'},
                {text: '<font color="orange">橙色</font>', action: function(e){
                        e.preventDefault();
                        $('.box[rel='+curNum+'] .bg').css('background-color', 'orange');
                    }
                },
                {text: '<font color="red">红色</font>', action: function(e){
                        e.preventDefault();
                        $('.box[rel='+curNum+'] .bg').css('background-color', 'red');
                    }
                },
                {text: '<font color="blue">蓝色</font>', action: function(e){
                        e.preventDefault();
                        $('.box[rel='+curNum+'] .bg').css('background-color', 'blue');
                    }
                },
                {text: '<font color="green">绿色</font>', action: function(e){
                        e.preventDefault();
                        $('.box[rel='+curNum+'] .bg').css('background-color', 'green');
                    }
                },
                {text: '<font color="purple">紫色</font>', action: function(e){
                        e.preventDefault();
                        $('.box[rel='+curNum+'] .bg').css('background-color', 'purple');
                    }
                },
                {text: '<font color="yellow">黄色</font>', action: function(e){
                        e.preventDefault();
                        $('.box[rel='+curNum+'] .bg').css('background-color', 'yellow');
                    }
                }*/
            // ]);
        }else{
            context.attach('.box[rel='+curNum+']', [
                {header: '操作'},
                {text: '编辑区域说明', action: function(e){
                        e.preventDefault();
                        layer.prompt({
                            title: '请输入区域说明',
                            formType: 2,
                            value: $('.box[rel='+curNum+'] .content').text()
                        }, function(value, index, elem){
                            layer.close(index);
                            var curCont = $('.box[rel='+curNum+'] .content');
                            curCont.text(value).css({
                                marginLeft : curCont.width()/2*-1,
                                marginTop : curCont.height()/2*-1
                            });
                        });
                    }
                },
                /*{text: '更改区域尺寸', action: function(e){
                        e.preventDefault();
                        layer.prompt({
                            title: '请输入区域尺寸（宽,高），最小值：30',
                            formType: 0,
                            value: $('.box[rel='+curNum+']').width()+","+$('.box[rel='+curNum+']').height()
                        }, function(value, index, elem){
                            var reg = /^[0-9]+,[0-9]+$/;
                            if(!reg.test(value)){
                                alert('输入格式不正确，例：100,200');
                                return;
                            }
                            var size = value.split(',');
                            var box = $('.box[rel='+curNum+']');
                            box.css({
                                width : size[0] < 30 ? 30 : size[0],
                                height : size[1] < 30 ? 30 : size[1]
                            });
                            layer.close(index);
                        });
                    }
                },*/
                // {text: '删除区域', action: function(e){
                //      e.preventDefault();
                //      $('.box[rel='+curNum+']').remove();
                //     }
                // },
                {divider: true},
                /*{header: '更改颜色'},
                {text: '<font color="orange">橙色</font>', action: function(e){
                        e.preventDefault();
                        $('.box[rel='+curNum+'] .bg').css('background-color', 'orange');
                    }
                },
                {text: '<font color="red">红色</font>', action: function(e){
                        e.preventDefault();
                        $('.box[rel='+curNum+'] .bg').css('background-color', 'red');
                    }
                },
                {text: '<font color="blue">蓝色</font>', action: function(e){
                        e.preventDefault();
                        $('.box[rel='+curNum+'] .bg').css('background-color', 'blue');
                    }
                },
                {text: '<font color="green">绿色</font>', action: function(e){
                        e.preventDefault();
                        $('.box[rel='+curNum+'] .bg').css('background-color', 'green');
                    }
                },
                {text: '<font color="purple">紫色</font>', action: function(e){
                        e.preventDefault();
                        $('.box[rel='+curNum+'] .bg').css('background-color', 'purple');
                    }
                },
                {text: '<font color="yellow">黄色</font>', action: function(e){
                        e.preventDefault();
                        $('.box[rel='+curNum+'] .bg').css('background-color', 'yellow');
                    }
                }*/
            ]);
        }
    }
    //添加区域
    $("#btn_add").click(function(){
    layer.open({
        type:1,
        area:['400px','400px'],
        title: '添加下级',
        content: $(".text-center"),
        shade: 0,
  //        btn: ['提交'],
  //        btn1: function(index, layero){
    //      console.log(layero)
  //        },
        // cancel: function(layero,index){
  //            layer.closeAll();
  //        }
    });

        //弹出区域说明输入框
    /*  layer.prompt({
            title: '请输入区域说明',
            formType: 2 //0:input,1:password,2:textarea
        }, function(value, index, elem){
            layer.close(index);
            createBox({
                text : value,
                id : 1,
                color : "rgb(255,0,0)",
                type : 1,
                width : 100,
                height : 100
            });
        });*/
    });
    //锁定区域
    $('#btn_lock').click(function(){
        if(lock){
            $(this).val("锁定区域");
            lock = false;
            $('.box .coor').show();
        }else{
            $(this).val("解锁区域");
            lock = true;
            $('.box .coor').hide();
        }
    });
    //获取所有区块
    $('#btn_save').click(function(){
        var data = [];
        $('.box').each(function(){
            var box = {};
            box['id'] = $(this).attr('dataId');
            box['type'] = $(this).attr('type');
            box['text'] = $(this).find('.content').text();
            box['color'] = $(this).find('.bg').css('background-color');
            box['height'] = $(this).height();
            box['width'] = $(this).width();
            box['pageX'] = $(this).position().left;
            box['pageY'] = $(this).position().top;
            //console.dir(box);
            var aa = JSON.stringify(box);
            data.push(aa);
        });
        let id = <?php echo $data;?>;
        // console.log(id.rid)
        let url = "{{ URL::asset('admin/locationSave') }}";
        let data1 = {
            _token: '{{ csrf_token() }}',
            id:id.rid,
            data: data
        }
        $.ajax({
           type: "POST",//规定传输方式
           url: url,//提交URL
           data: data1,//提交的数据
           success: function(data){
               console.log(data)
                layer.msg(data.resulMsg);
           }
        });
    });
    //创建拖拽方法
    $("#canvas").mousedown(function(e){
        var canvas = $(this);
        e.preventDefault();
        var pos = $(this).position();
        console.log(33)
        this.posix = {'x': e.pageX - pos.left, 'y': e.pageY - pos.top};
        $.extend(document, {'move': true, 'move_target': this, 'call_down' : function(e, posix){
            canvas.css({
                'cursor': 'move',
                'top': e.pageY - posix.y,
                'left': e.pageX - posix.x
            });
        }, 'call_up' : function(){
            canvas.css('cursor', 'default');
        }});
    }).on('mousedown', '.box', function(e) {
        if(lock) return;
        var pos = $(this).position();
        this.posix = {'x': e.pageX - pos.left, 'y': e.pageY - pos.top};
        // var isMove = true;
     //   var div_x = e.pageX - $(moveDiv).offset().left;
     //   var div_y = e.pageY - $(moveDiv).offset().top;
     //   $(document).mousemove(function (e) {
     //       if (isMove) {
     //           var obj = $(moveDiv);
     //           obj.css({"left":e.pageX - div_x, "top":e.pageY - div_y});
     //       }
     //   }).mouseup(
     //       function () {
     //       isMove = false;
     //   });
        // console.log(pos)
        $.extend(document, {'move': true, 'move_target': this});
        e.stopPropagation();
    }).on('mousedown', '.box .coor', function(e) {
        console.log(2)
        var $box = $(this).parent();
        var posix = {
                'w': $box.width(),
                'h': $box.height(),
                'x': e.pageX,
                'y': e.pageY
            };
        $.extend(document, {'move': true, 'call_down': function(e) {
            $box.css({
                'width': Math.max(30, e.pageX - posix.x + posix.w),
                'height': Math.max(30, e.pageY - posix.y + posix.h)
            });
        }});
        e.stopPropagation();
    });
    var loadData = <?php echo $data;?>;
    
    $.each(loadData, function(i, row){
        createBox(row);
    });

    var url = window.location.pathname;
    var str = url.slice(7,13)
    
    let timer = setInterval(function () {
        var url1 = window.location.pathname;
        var str1 = url1.slice(7,13)
        console.log(str1)
        if (str1 === str) {
            console.log(str)
        }else{
            console.log(333) 
            clearInterval(timer);
        };
    }, 2000);
});

</script>
</body>
</html>